package com.lanou.sinasports.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.lanou.sinasports.R;
import com.lanou.sinasports.adapter.NewsHotAdapter;
import com.lanou.sinasports.beans.GsonNewsHot;
import com.lanou.sinasports.beans.NewsHot;
import com.lanou.sinasports.utils.GsonRequest;
import com.lanou.sinasports.utils.VolleySingleton;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by dllo on 16/1/10.
 */
public class NewsHotFragment extends Fragment {
    private ListView listView;
    private ViewPager viewPager;
    private List<View> dots;
    private int currentItem;
    private int oldPosition = 0;
    private NewsHotAdapter adapter;
    private List<NewsHot> data;
    private VolleySingleton queue;
    private String url = "http://platform.sina.com.cn/sports_client/feed?app_key" +
            "=2586208540&pid=29&len=20&news_type=0%2C2%2C3%2C101%2C102%2C103%2C106%2C107%2C108&feed_id" +
            "=1009&pdps_params=%7B%22app%22%3A%7B%22timestamp%22%3A%221452066794666%22%2C%22os%22%3A%22Android%22%2C%22model%22%3A%22MI+4LTE%22%2C%22device_" +
            "type%22%3A%224%22%2C%22osv%22%3A%224.4.4%22%2C%22name%22%3A%22cn.com.sina.sports%22%2C%22carrier%22%3A%22%E4%B8%AD%E5%9B%BD%E7%A7%BB%E5%8A%A8%22%2C%22device_" +
            "id%22%3A%22866500020074540%22%2C%22make%22%3A%22MI+4LTE%22%2C%22channel%22%3A%22%22%2C%22connection_" +
            "type%22%3A%222%22%2C%22version%22%3A30000105%2C%22ip%22%3A%22fe80%3A%3A1a59%3A36ff%3Afe27%3A43dd%25wlan0%22%7D%7D";
    private Context context;
    private ViewPagerAdapter viewPagerAdapter;
    private ScheduledExecutorService scheduledExecutorService;
    private TextView title;

    private int imageIds[] = new int[5];
    private String[] titles = new String[5];

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_newshot, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        listView = (ListView) view.findViewById(R.id.lv_newshot);
        viewPager = (ViewPager) view.findViewById(R.id.vp_lunbo);
        dots = new ArrayList<>();
        dots.add(view.findViewById(R.id.dot_0));
        dots.add(view.findViewById(R.id.dot_1));
        dots.add(view.findViewById(R.id.dot_2));
        dots.add(view.findViewById(R.id.dot_3));
        dots.add(view.findViewById(R.id.dot_4));

        title = (TextView) view.findViewById(R.id.tv_lunbo_title);
    }

    private class ViewPagerAdapter extends PagerAdapter {
        private List<NewsHot> data;
        private ImageLoader imageLoader;
        private List<ImageView> images;


        public ViewPagerAdapter(List<NewsHot> data) {
            imageLoader = VolleySingleton.getImageLoader();
            images = new ArrayList<ImageView>();

            this.data = data;
            for (int i = 0; i < data.size(); i++) {
                NetworkImageView imageView = new NetworkImageView(context);
                imageView.setDefaultImageResId(R.mipmap.ic_main_tab_match_p);
                imageView.setErrorImageResId(R.mipmap.ic_main_tab_team_p);
                imageView.setImageUrl(data.get(i).getImage(), imageLoader);
                titles[i] = data.get(i).getTitle();
                images.add(imageView);
            }
        }

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            view.removeView(images.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            view.addView(images.get(position));
            return images.get(position);
        }

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        data = new ArrayList<>();



        queue = VolleySingleton.getInstance();


        GsonRequest<GsonNewsHot> request = new GsonRequest<GsonNewsHot>(url, GsonNewsHot.class, new Response.Listener<GsonNewsHot>() {
            @Override
            public void onResponse(GsonNewsHot gsonNewsHot) {
                List<Object> list = gsonNewsHot.getResult().getData();
                List<NewsHot> newsHots1 = new ArrayList<NewsHot>();
                List<NewsHot> newsHot2 = new ArrayList<NewsHot>();
                for (int i = 0; i < list.size(); i++) {
                    Object obj = list.get(i);
                    if (obj instanceof Map) {
                        Map map = (Map) obj;
                        String model = (String) map.get("model");
                        List<Object> data = (List<Object>) map.get("data");
                        for (int j = 0; j < data.size(); j++) {

                            Map innerMap = (Map) data.get(j);
                            String id = (String) innerMap.get("id");
                            String url = (String) innerMap.get("url");
                            String title = (String) innerMap.get("title");
                            String image = (String) innerMap.get("image");
                            String jktitle = (String) innerMap.get("jktitle");
                            String jksummary = (String) innerMap.get("jksummary");
                            NewsHot hot = new NewsHot();

                            hot.setId(id);
                            hot.setUrl(url);
                            hot.setImage(image);
                            hot.setTitle(title);



                            hot.setJktitle(jktitle);
                            hot.setJksummary(jksummary);



                            if (i == 0) {
                                newsHots1.add(hot);
                            } else if (i == 1) {
                                newsHot2.add(hot);
                            }


                        }
                    }

                }
                titles = new String[newsHots1.size()];
                for (int i = 0; i < titles.length; i++) {
                    titles[i] = newsHots1.get(i).getTitle();
                }


                adapter = new NewsHotAdapter(context, newsHot2);
                listView.setAdapter(adapter);

                viewPagerAdapter = new ViewPagerAdapter(newsHots1);

                viewPager.setAdapter(viewPagerAdapter);
//                title.setText(titles[0]);

                viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                        title.setText(titles[position]);
                        dots.get(position).setBackgroundResource(R.drawable.dot_focused);
                        dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);


                        oldPosition = position;
                        currentItem = position;

                    }

                    @Override
                    public void onPageSelected(int position) {

                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue._addRequest(request);

    }


    @Override
    public void onStart() {
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(new ViewPageTask(), 5,5, TimeUnit.SECONDS);
    }


    private class ViewPageTask implements Runnable {

        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageIds.length;
            handler.sendEmptyMessage(0);

        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            viewPager.setCurrentItem(currentItem);
        }
    };


}
